package com.jnr.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import se.codevision.jinterlink.JInterLink;

import com.ajr.core.Settings;
import com.ajr.core.oscommerce.OSCommerceAction;
import com.ajr.core.visma.CustomersAction;
import com.ajr.core.visma.ExportResult;
import com.ajr.util.MessageBundle;
import com.ajr.util.ParamUtil;

/**
 * Servlet implementation class SubmitCustomer
 */
public class SubmitCustomer extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(SubmitCustomer.class);

       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SubmitCustomer() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


//		logger.info("properties "+properties);
		String system = Settings.getInstance().getSystemPath();
		String company =  Settings.getInstance().getCompanyPath();
		String s =  Settings.getInstance().getLibraryPath();
		
		String page = "1";
		String orderId = "0";
		String customerd = "0";
		if(request.getParameter("page") != null && request.getParameter("page").length() > 0) {
			page = request.getParameter("page");
		}

		String redirecturl = request.getParameter("redirecturl");


		PrintWriter printWriter = response.getWriter();
		String message = "";
		
		if(!Settings.getInstance().isReadConfigureOnce()) {
			Settings.getInstance().loadDataBaseConfigurations();
		}
		

		ExportResult exportedCustomer = new ExportResult();;
		try {

			/*if(!Settings.getInstance().isExportSpcsJInterTables() 
					|| !OSCommerceAction.isCustomerExported(customerd)) {
				
			}*/
			JInterLink j = JInterLink.getInstance();
			j.open(s, system, company);
			// Article article = JInterLinkRegisterFactory.createArticle();

			customerd = request.getParameter("customer_id");

			if (customerd != null && customerd.length() > 0) {
				CustomersAction customersAction = new CustomersAction();
				exportedCustomer = customersAction.insertCustomer(Integer.parseInt(customerd),true);
				
				message= exportedCustomer.getResultMessage();

			}else {
				exportedCustomer.setMessage(ExportResult.OSC_CUSTOMER_INVALID_CODE,MessageBundle.getMessage("provide.valid.customerid"));				
			}

			j.close();


		} catch (Exception e) {
			exportedCustomer.setMessage("warning", e.getMessage());
//			exportResult.setError();
			exportedCustomer.setStatus(false);
			
			printWriter.write("Unable to export the order " + e);
			logger.error("Unable to export order", e);
			// TODO: handle exception
		}
		

		if(redirecturl != null && redirecturl.length() > 0) {
//			String url = (new URLDecoder().decode(redirecturl))+"&message="+exportResult.getMessage();
			int seperator = redirecturl.indexOf("?");
			String redirectUrlPart = redirecturl.substring(0,seperator);	
			String paramspart =  redirecturl.substring(seperator+1);
			HashMap paramsMap = ParamUtil.getParamsMap(paramspart);

//			paramsMap.put("messagecode",exportedCustomer.getMessageCode());
			paramsMap.put("message",exportedCustomer.getMessage());
			paramsMap.put("exportStatus",exportedCustomer.getStatusCode());
			
			String url = redirectUrlPart+"?"+ParamUtil.getParams(paramsMap);
			logger.info("redirecting url "+url);
			response.sendRedirect(url);
			return;
		}else {
			response.setContentType("text/html");
			response.setHeader("expires", "-1");
			
//			printWriter.write(exportedCustomer.getXMLResponse());
			printWriter.write(exportedCustomer.getHtmlResponse(page,orderId,customerd));
		}

		

		


		// String s1 =
		// OrderClauseExample.readOsCommerceOrders(OrderReader.readIds());

		// logger.info(s1);

		/*
		 * OrderRows orderrows =
		 * JInterLinkRegisterFactory.createOrderRowList(5);
		 * 
		 * for (int i = 0; i < orderrows.size(); i++) {
		 * 
		 * logger.info(orderrows.get(i).getArticleType());
		 * 
		 * }
		 */


	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
